# --*-- coding:utf-8 --*--

import json
import requests
import urllib.parse
import warnings
import time
import random

warnings.filterwarnings("ignore")


class Zhitongche(object):

	token = None

	# 读取cookie
	def __init__(self,cookie):
		super(Zhitongche, self).__init__()
		self.cookie = cookie
		# 获取token
		self.session = requests.session()
		self.headers = {
			'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
			'X-Requested-With': 'XMLHttpRequest',
			'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
			'Host': 'subway.simba.taobao.com'
			}
		url = 'https://subway.simba.taobao.com/entry/login.htm'
		resp = self.session.get(url, verify=False, headers=self.headers, cookies = self.cookie)
		url = 'https://subway.simba.taobao.com/bpenv/getLoginUserInfo.htm'
		data = urllib.parse.urlencode({'_referer': '/home'})
		resp = self.session.post(url, headers=self.headers, data=data, verify=False, cookies = self.cookie)
		self.token = resp.json()['result']['token']
		# print (self.token)






	# 人群添加
	def get_plan_info(self):

		# # 获取token
		# # print '获取token',self.cookie
		# url = 'https://subway.simba.taobao.com/entry/login.htm'
		# resp = self.session.get(url, verify=False, headers=self.headers, cookies=self.cookie)
		# url = 'https://subway.simba.taobao.com/bpenv/getLoginUserInfo.htm'
		# data = urllib.parse.urlencode({'_referer': '/home'})
		# resp = self.session.post(url, headers=self.headers, data=data, verify=False, cookies=self.cookie)
		# self.token = resp.json()['result']['token']

		# 获取计划信息
		url = 'https://subway.simba.taobao.com/campaign/getCampaignDetailInfo.htm'

		data = urllib.parse.urlencode({'sla': 'json',
									   'isAjaxRequest': 'true',
									   'token': self.token,
									   '_referer': ''})
		payload = {'type': ''}
		resp = requests.post(url, data=data, headers=self.headers, verify=False, params=payload, cookies=self.cookie)
		plan_list = []

		for i in resp.json()['result']:
			plan_info = []
			plan_info.append(i['title'])
			plan_info.append(i['type'])  # 计划类型
			plan_info.append(i['discount'])
			plan_info.append(i['bidSettingInfo'][:-2])
			plan_info.append(i['platformInfo'])  # 投放平台
			plan_info.append(i['campaignId'])
			plan_list.append(plan_info)
		# campaignId = i['campaignId']

		# print(plan_list)
		return plan_list

	def get_plan_goods(self, campaignId):

		''' 获取计划下商品信息 '''

		url1 = 'https://subway.simba.taobao.com/testing/listADGroup.htm'
		url2 = 'https://subway.simba.taobao.com/adgroup/adGroupList.htm'
		payload = {
			'queryVO': '{"pageNumber":1,"pageSize":200,"queryTitle":"","queryState":"","campaignId":' + campaignId + '}'}
		data = urllib.parse.urlencode({'sla': 'json',
									   'isAjaxRequest': 'true',
									   'token': self.token,
									   '_referer': '/campaigns/standards/adgroups/index?type=item&campaignId=' + campaignId})
		resp = requests.post(url1, headers=self.headers, data=data, verify=False, params=payload, cookies=self.cookie)

		if resp.json()['result'] == None:
			resp = requests.post(url2, headers=self.headers, data=data, verify=False, params=payload,
								 cookies=self.cookie)  # 获取计划下商品信息有2个不同url
			if resp.json()['result'] == None:
				return " "
		plan_goods_list = []
		try:  # 不确定每个计划下是否有商品尝试获取商品信息
			for j in resp.json()['result']['items']:
				goods_info_list = []
				goods_info_list.append(j['adGroupDTO']['title'])
				goods_info_list.append(j['adGroupDTO']['displayDefaultPrice'])
				goods_info_list.append(j['adGroupDTO']['mobileDiscount'])
				goods_info_list.append(j['adGroupDTO']['productId'])
				goods_info_list.append(j['adGroupDTO']['adGroupId'])
				plan_goods_list.append(goods_info_list)
			print(plan_goods_list)
			return plan_goods_list
		except:
			print(" ")
			return " "

		# print title,mobileDiscount,displayDefaultPrice,productId

	def get_population_information(self, key):

		''' 获取人口属性人群信息 '''  # productId=101001005
		tagDict = {}
		url = 'https://subway.simba.taobao.com/crowdTemplate/getLayoutExt.htm?productId=101001005&bizType=1&firstCat=50010788'
		resp = self.session.get(url, headers=self.headers, verify=False, cookies=self.cookie)
		crowd_info = resp.json()['result'][1]['dimDTOs']
		for type_list in crowd_info:
			for types in type_list["tagOptions"]:
				if key == types["tagName"]:
					tagDict["dimId"] = str(types['dimId'])
					tagDict["tagName"] = types['tagName'].encode('utf8')
					tagDict["tagId"] = str(types["tagId"])
					tagDict["optionGroupId"] = str(types["optionGroupId"])
		return tagDict

	def add_crowd(self, productId, tagList, price, adgroup_id):

		''' 为计划添加人群 '''
		result_List  = []
		for k in tagList:
			null_List = []
			for i in k['item']:
				null_List.append(self.get_population_information(i))
			# print (null_List)
			# null_List = str(null_List).encode('latin-1').decode('unicode_escape').replace("'", '"')
			# null_List = null_List.encode(encoding="utf-8")
			# print (null_List)
			for s in null_List:
				s['tagName'] = (s['tagName'].decode(encoding="utf-8"))

			null_List = str(null_List).replace("'", '"')
			# print (null_List)

			targetings = '[{"crowdDTO":{"extParam":{"firstCat":"50010788"},"templateId":12,"name":' + '"' + str(k) + '"' + ',"tagList":' + null_List + '},"isDefaultPrice":0,"priceMode":1,"discount":' + str(
				100 + int(price)) + '}]'
			url = 'https://subway.simba.taobao.com/adgroupTargeting/add.htm'
			data = urllib.parse.urlencode({'productId': productId,
										   'bizType': '1',
										   'sla': 'json',
										   'isAjaxRequest': 'true',
										   'adgroupId': adgroup_id,
										   'targetings': targetings,
										   'token': self.token
										   # '_referer':'/campaigns/standards/adgroups/items/detail?tab=prime-crowd&campaignId=49264981&adGroupId=860141961'
										   })
			resp = self.session.post(url, headers=self.headers, data=data, verify=False, cookies=self.cookie)
			time.sleep(random.uniform(1,2))
			result_List.append(resp.json())
		return result_List






	# 地域设置
	def get_area_info(self, key):

		''' 获取地域信息 '''

		url = 'https://g.alicdn.com/mm/subway/2018.0523.133150/components/??region-selector/regions-min.js,region-searchbar/index-min.js?t=2018.js'
		resp = self.session.get(url, verify=False)
		area_str = resp.text.split('return')[1].split('});')[0]
		str_dict1 = area_str.replace('name', '"name"')
		str_dict2 = str_dict1.replace('code', '"code"')
		str_dict3 = str_dict2.replace('contains', '"contains"')
		# print json.loads(str_dict3)
		# 比较参数是否为大区名称，若是获取所有省ID
		for area in json.loads(str_dict3):
			if area['name'] == key:
				province_list = []
				for province in area['contains']:
					province_list.append(province['code'])
				return province_list
		# 比较参数是否为省名称，若是获取所有市ID
		for province in json.loads(str_dict3):
			city_list = []
			for city in province['contains']:
				if city['name'] == key:
					try:
						for s in city['contains']:
							city_list.append(s['code'])
						return city_list
					except:
						city_list.append(city['code'])
						return city_list
		# 比较参数是否为市名称，若是获取该市ID
		for province in json.loads(str_dict3):
			city_list = []
			for city in province['contains']:
				try:
					for s in city['contains']:
						if s['name'] == key:
							city_list.append(s['code'])
							return city_list
				except:
					if city['name'] == key:
						city_list.append(city['code'])
						return city_list

	def set_area(self, campaignId, area_list, type_code):
		# print(campaignId, area_list, type_code)

		if int(type_code) == 2:  # 2 仅把以下地域作为投放地域
			''' 设置地域 '''
			areaState = str(area_list).split('[')[1].split(']')[0].replace(' ', '')
			# print(areaState)
			url = 'https://subway.simba.taobao.com/area/update.htm'
			payload = {'campaignId': campaignId, 'areaState': areaState}
			data = urllib.parse.urlencode({'sla': 'json',
										   'isAjaxRequest': 'true',
										   'token': self.token,
										   '_referer': '/campaigns/standards/adgroups/index?type=item&campaignId=' + campaignId})
			resp = self.session.post(url, headers=self.headers, data=data, params=payload, verify=False,
									 cookies=self.cookie)
			# print(payload)
			# print(resp.status_code)
			return resp.status_code

		else:  # 1 原有地域设置添加已下地域

			# 获取原先设置地域并且合并现在加上的地域
			url = 'https://subway.simba.taobao.com/area/get.htm'
			payload = {'campaignId': campaignId}
			data = urllib.parse.urlencode({'sla': 'json',
										   'isAjaxRequest': 'true',
										   'token': self.token,
										   '_referer': '/campaigns/standards/adgroups/index?type=item&campaignId=' + campaignId})

			Resp = self.session.post(url, headers=self.headers, data=data, params=payload, verify=False,
									 cookies=self.cookie)
			splitAreaStateList = Resp.json()['result']['areaState']
			areaState = str(area_list).split('[')[1].split(']')[0].replace(' ', '') + ',' + splitAreaStateList

			# 地域设置
			url = 'https://subway.simba.taobao.com/area/update.htm'
			payload = {'campaignId': campaignId, 'areaState': areaState}
			data = urllib.parse.urlencode({'sla': 'json',
										   'isAjaxRequest': 'true',
										   'token': self.token,
										   '_referer': '/campaigns/standards/adgroups/index?type=item&campaignId=' + campaignId})
			resp = self.session.post(url, headers=self.headers, data=data, params=payload, verify=False,
									 cookies=self.cookie)
			# print(resp.status_code)
			return resp.status_code

# # 测试
# if __name__ == '__main__':

# 	cookie = {'uc3': 'id2=&nk2=&lg2=', 't': '0aaed07dcf28e04a5eb8507757ad365b', 'skt': 'e2aefab1259abc71', 'v': '0', 'unb': '3926008482', 'csg': '1cb2b50a', 'uc1': 'cookie14=UoTfL8nFEky4jg%3D%3D&lng=zh_CN', 'cookie2': '13c3c8792eb34998329a0f24f5fa2292', '_tb_token_': '7bbee710e665e', 'sn': '%E9%9C%B2%E6%98%93%E8%B1%AA%E4%B8%B9%E6%97%97%E8%88%B0%E5%BA%97%3A%E8%BF%90%E8%90%A59', 'tracknick': '', 'cna': 'ZL77E1ldHHsCAW+s5i/3rI83', 'isg': 'BCUlD2ClklGaxfYNn1x8pqObOOFfYtn0tg7Y2CcK4dxrPkWw77LpxLN9zCRIJfGs', 'x': '2456413021'}


# 	zhitongche = Zhitongche(cookie)
# #
#
# # # 	# 获取计划列表测试
# 	print(zhitongche.get_plan_info())
#
# # 	# 获取计划下商品信息
# 	campaignId = '53923952'
# 	print(zhitongche.get_plan_goods(campaignId))
#
# 	# # 获取人口属性人群信息
	# print(zhitongche.get_population_information('男'))
#
#
# # 	# 为计划添加人群
# 	# info_list = [{'productId':'101001005'},{}]
	# productId = '101001005'
	# tagList = [{'item': ['18岁以下', '女', '300元以下']}, {'item': ['18岁以下', '男', '300元以下']}, {'item': ['18-24岁', '女', '300元以下']}, {'item': ['18-24岁', '男', '300元以下']}]
	# price = '5'
	# adgroup_id = '924722549'
	# zhitongche.add_crowd(productId, tagList, price, adgroup_id)
#
# 	# 获取地域信息
# 	key = u'湖北'
# 	campaignId = '21437045'  #计划ID
# 	area_list = zhitongche.get_area_info(key)
# 	print(area_list)
# 	areaState = str(area_list).split('[')[1].split(']')[0].replace(' ','')
# 	print(areaState)
#
# 	# # # 地域设置
# zhitongche.set_area(campaignId,area_list)
